package www.bw.com.shiro.realms;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import www.bw.com.beans.User;
import www.bw.com.service.UserService;

import java.util.HashSet;
import java.util.Set;


public class MyRealm  extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    //返回权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //根据用户的账号查询具有的权限和角色，封装到SimpleAuthorizationInfo，返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


       //查询角色和权限
        String userName= (String) principals.getPrimaryPrincipal();
        Set<String> roles=userService.findRolesByUserName(userName);
        Set<String> permissions=userService.findPermissionsByUserName(userName);
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }


    //返回认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //info实际就是根据账号把数据库中的密码查询出来，封装起来了
        SimpleAuthenticationInfo info = null;
//        UsernamePasswordToken token1 = (UsernamePasswordToken)token;
//        token1.getUsername();
        String username = (String)token.getPrincipal();
        User user=userService.findUserByUserName(username);
        //如果账号不存在
        if(user==null){
            throw  new UnknownAccountException("账号不存在");
        }


        info = new SimpleAuthenticationInfo(username,user.getPassword(),getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt())); //设置盐值
        return info;
    }

    @Override
    public String getName() {
        return "自定义Realm";
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("12345","1234",1024);
        System.out.println(md5Hash.toString());
//        SimpleHash hash = new SimpleHash("md5","12345","1234",1024);
//        System.out.println(hash.toString());
    }
}
